///PHILOTES Source Code.  (C)2012 PhiloLabs

#include "OgreStableHeaders.h"
#include "OgreUserObjectBindings.h"

namespace Ogre {

	Any UserObjectBindings::msEmptyAny;
	
	//--------------------------------------------------------------------------
	UserObjectBindings::UserObjectBindings()
	{
		mAttributes = NULL;
	}

	//--------------------------------------------------------------------------
	UserObjectBindings::~UserObjectBindings()
	{
		clear();
	}

	//-----------------------------------------------------------------------
	void UserObjectBindings::setUserAny( const Any& anything )
	{
		// Allocate attributes on demand.
		if (mAttributes == NULL)
			mAttributes = PHILO_NEW UserObjectBindings::Attributes;
		
		mAttributes->mKeylessAny = anything;
	}

	//-----------------------------------------------------------------------
	const Any& UserObjectBindings::getUserAny( void ) const
	{
		// Allocate attributes on demand.
		if (mAttributes == NULL)
			mAttributes = PHILO_NEW UserObjectBindings::Attributes;

		return mAttributes->mKeylessAny;
	}

	//-----------------------------------------------------------------------
	void UserObjectBindings::setUserAny(const String& key, const Any& anything)
	{
		// Allocate attributes on demand.
		if (mAttributes == NULL)
			mAttributes = PHILO_NEW UserObjectBindings::Attributes;

		// Case map doesn't exists.
		if (mAttributes->mUserObjectsMap == NULL)
			mAttributes->mUserObjectsMap = new UserObjectsMap;

		(*mAttributes->mUserObjectsMap)[key] = anything;
	}	

	//-----------------------------------------------------------------------
	const Any& UserObjectBindings::getUserAny(const String& key) const
	{
		// Allocate attributes on demand.
		if (mAttributes == NULL)
			mAttributes = PHILO_NEW UserObjectBindings::Attributes;

		// Case map doesn't exists.
		if (mAttributes->mUserObjectsMap == NULL)
			return msEmptyAny;

		UserObjectsMapConstIterator it = mAttributes->mUserObjectsMap->find(key);

		// Case user data found.
		if (it != mAttributes->mUserObjectsMap->end())
		{
			return it->second;
		}
		
		return msEmptyAny;
	}

	//-----------------------------------------------------------------------
	void UserObjectBindings::eraseUserAny(const String& key)
	{
		// Case attributes and map allocated.
		if (mAttributes != NULL && mAttributes->mUserObjectsMap != NULL)
		{
			UserObjectsMapIterator it = mAttributes->mUserObjectsMap->find(key);

			// Case object found -> erase it from the map.
			if (it != mAttributes->mUserObjectsMap->end())
			{
				mAttributes->mUserObjectsMap->erase(it);
			}
		}
	}

	//-----------------------------------------------------------------------
	void UserObjectBindings::clear() const
	{
		if (mAttributes != NULL)
		{			
			PHILO_DELETE mAttributes;
			mAttributes = NULL;
		}
	}
}
